<script>
import { deepClone } from "@/utils/index";
import { ComponentConfigList, Components } from "./custom/config.js";
import CustomeTabs from "./Tabs.vue";
import { getDataBySQL } from '@/api/databasemanage/datasource';
import {getDataDetail} from '@/api/system/dataitem';
import { getDbLinksTestSql } from '@/api/databasemanage/databaselink';
const ComponentList = ComponentConfigList;
Components["CustomeTabs"] = CustomeTabs;
export default {
  name: "FormParser",
  components: Components,
  props: {
    conf: {
      type: Object,
      required: true
    },
    formFieldInfo: {
      type: Object
    },
    formData: {
      type: Object
    },
    formInfos: {
      type: Object
    },
    taskComment: {
      type: Array
    },
    type: {
      type: Number,
      default: 0
    },
    index: {
      type: Number,
      default: 0
    },
    isEdit: {
      type: Number,
      default: 1
    },
  },
  data() {
    return {
      // isEdit:1,// 1 新增 2 查看 3 编辑
      formType: "",
      formIndex: 0,
      formOperationObject: {
        formModel: {}, // 绑定数据
        formRules: {}, // 绑定规则
        mainTableName: ""
      },
      autoCompleteConf:{},
      slots: [],
      formConf: {}
    };
  },
  created() {
    this.formType = this.type;
    this.formIndex = this.index;
    this.formConf = deepClone(this.conf);
    if (!this.formConf.fields) {
      this.$message.error(this.$t('workFlow.printCurrentPage.hintAbnormal'));
      return false;
    }
    if (
      !this.formFieldInfo ||
      !this.formFieldInfo.children ||
      this.formFieldInfo.children.length == 0
    ) {
      this.$message.error(this.$t('workFlow.printCurrentPage.hintNoPermission'));
      return false;
    }
    this.changeFields();
    this.changeData();
  },
  mounted () {
    this.$event.$on('openFilterableDataDialog',conf=>{
      this.autoCompleteConf = conf;
      this.slots = [];

      var listeners = {
        onHandler: conf.avueType=="mutiple-popup"?this.mutipleFilterableCallBack:this.filterableCallBack
      }
      this.slots.push( 
        <filterable-data-list 
        conf={this.autoCompleteConf} 
		type={conf.avueType=="mutiple-popup"?'mutiple':'single'}
        {...{ on: listeners }}>
        </filterable-data-list>
      );
    });
  },
  render(h) {
    return (
      <el-row gutter={this.formConf.gutter}>
        <el-form
          size={this.formConf.size}
          label-position={this.formConf.labelPosition}
          disabled={this.formConf.disabled}
          label-width={`${this.formConf.labelWidth}px`}
          ref={this.formConf.formRef}
          props={{
            model: this.formOperationObject.formModel[
              this.formOperationObject.mainTableName
            ]
          }}
          rules={this.formOperationObject.formRules}
        >
          {this.renderForm(h)}
        </el-form>
         {this.slots}
      </el-row>
    );
  },
  methods: {
	mutipleFilterableCallBack(data){
		if(!this.autoCompleteConf){
		  return false;
		}
		//弹窗关闭前回填数据  如果有选择数据项
		if(data){
		  let fields = this.formConf.fields;
		  if(this.autoCompleteConf.autoBindFields){
		    let autoBindFields = JSON.parse(this.autoCompleteConf.autoBindFields) || {};
			let showField = this.autoCompleteConf.dataType == 'dataItem' ? 'F_ItemName':this.autoCompleteConf.showField;
			let saveField = this.autoCompleteConf.dataType == 'dataItem' ? 'F_ItemValue':this.autoCompleteConf.saveField;
		    if (data && data.length > 0) {
				let arr = [],arr2=[]
				data.forEach(it => {
				  arr.push(it[showField])
				  arr2.push(it[saveField])
				})
				//自己赋值
				this.selfSetDefaultVal(fields,autoBindFields,arr.join(','),arr2.join(','),this.autoCompleteConf.formId);
			  }
		    
		  }
		}
		//关闭弹窗
		this.slots = [];
	},
    filterableCallBack(data){
      if(!this.autoCompleteConf){
        return false;
      }
      
      //弹窗关闭前回填数据  如果有选择数据项
      if(data){
    	  
        let fields = this.formConf.fields;
        if(this.autoCompleteConf.autoBindFields){
          let autoBindFields = JSON.parse(this.autoCompleteConf.autoBindFields) || {};
          let showField = this.autoCompleteConf.dataType == 'dataItem' ? 'F_ItemName':this.autoCompleteConf.showField;
    	  let saveField = this.autoCompleteConf.dataType == 'dataItem' ? 'F_ItemValue':this.autoCompleteConf.saveField;
          this.setDefaultVal(fields,autoBindFields,data);
          //自己赋值
          this.selfSetDefaultVal(fields,autoBindFields,data[showField],data[saveField],this.autoCompleteConf.formId);
        }
      }
      //emit 改变值
      this.$event.$emit('updateFormConf',this.formConf);
      //关闭弹窗
      this.slots = [];
    },
    setDefaultVal(fields,autoBindFields,data){
      fields.map((item,index)=>{
        if(item?.__config__?.componentName == 'avue-tabs'){
          let childrenObj = item?.__config__?.childrenObj || {};
          for(let key in childrenObj){
            let children = childrenObj[key];
            this.setDefaultVal(children,autoBindFields,data);
          }
        }else{
          //找到对应formId 元素  key值为存储的对应formId         
    	  if(Object.prototype.toString.call(autoBindFields) === '[object Array]'){
    		  autoBindFields.forEach(el=>{
    			if(el.component==item.__config__.formId){
    			  item.__config__.defaultValue= data[el.bindField];
    			}
    		  })
    	  }else{
    		 if(autoBindFields.hasOwnProperty(item?.__config__?.formId)){
    		   //按绑定的自定义字段赋值
    		   item.__config__.defaultValue = data[autoBindFields[item.__config__.formId]];
    		 } 
    	  }
        }
      });
    },
    selfSetDefaultVal(fields,autoBindFields,data,value, formId){
      fields.map((item,index)=>{
        if(item?.__config__?.componentName == 'avue-tabs'){
          let childrenObj = item?.__config__?.childrenObj || {};
          for(let key in childrenObj){
            let children = childrenObj[key];
            this.selfSetDefaultVal(children,autoBindFields,data,value, formId);
          }
        }else{
          if(item?.__config__?.formId == formId){
            item.__config__.defaultValue = value;
    		item.__config__.showValue = data;
          }
        }
    	
    		
      });
    },
    getAuthorityList() {
      //表单权限
      let authorityList = new Map();
      if (
        this.formFieldInfo &&
        this.formFieldInfo.children &&
        this.formFieldInfo.children.length > 0
      ) {
        let filedsSettingAuthority = this.formFieldInfo.children;
        filedsSettingAuthority.forEach(element => {
          let key = element.formId;
          authorityList.set(key, element);
        });
      }
      return authorityList;
    },
    getTaskCommentList() {
      //处理意见框组件
      let taskCommentList = {};
      if (this.taskComment && this.taskComment.length > 0) {
        this.taskComment.forEach(element => {
          if (
            element.approvalcomponents &&
            element.approvalcomponents.length > 0
          ) {
            element.approvalcomponents.forEach(taskCommentId => {
              if (taskCommentList[taskCommentId]) {
                taskCommentList[taskCommentId].push(element);
              } else {
                taskCommentList[taskCommentId] = [element];
              }
            });
          }
        });
      }
      return taskCommentList;
    },
    defaultValidator(conf) {
      const self = this;
      return (rule, value, callback) => {
        const defaultValue = conf.__config__.defaultValue;
        if (conf.readonly) {
          //只读属性
          callback();
        }
        if (defaultValue) {
          callback();
        } else {
          const msg =
            conf.placeholder === undefined
              ? `${conf.__config__.label}不能为空`
              : conf.placeholder;
          callback(new Error(msg));
        }
      };
    },
    quantityValidator(conf) {
      const self = this;
      return (rule, value, callback) => {
        const defaultValue = conf.__config__.defaultValue;
        if(conf.readonly){//只读属性
          callback()
        }else{
          let ruleMessage = '';
          if(conf.min&&conf.max){
            ruleMessage = `${conf.__config__.label}最小数量为${conf.min}，最大数量为${conf.max}`;
            if(defaultValue&&(defaultValue.length<conf.min||defaultValue.length>conf.max)){
              callback(new Error(ruleMessage));
            }else{
              if(conf.min){
                ruleMessage = `${conf.__config__.label}最小数量为${conf.min}`;
                if(defaultValue&&defaultValue.length<conf.min){
                  callback(new Error(ruleMessage));
                }else{
                  callback()
                }
              }else if(conf.max){
                 ruleMessage = `${conf.__config__.label}最大数量为${conf.max}`;
                if(defaultValue&&defaultValue.length>conf.max){
                  callback(new Error(ruleMessage));
                }else{
                  callback()
                }
              }else{
                callback()
              }
               
            }
          }
        }
      };
    },
    patternValidator(pattern, msg,conf) {
      const self = this;
      return (rule, value, callback) => {
        const defaultValue = conf.__config__.defaultValue;
        if (conf.readonly) {
          //只读属性
          callback();
        }
        if (pattern.test(defaultValue)) {
          callback();
        } else {
          callback(new Error(msg));
        }
      };
    },
    switchValidator(conf) {
      return (rule, value, callback) => {
         callback();
      };
    },
    uploadValidator(conf) {
      const self = this;
      return (rule, value, callback) => {
        if(conf.__config__.defaultValue){
          callback();
        }else{
          const msg =
            (conf.placeholder === undefined
              ? `${conf.__config__.label}不能为空`
              : conf.placeholder) + "必须上传！";
          callback(new Error(msg));
        }
      };
    },
    checkboxValidator(conf) {
      const self = this;
      return (rule, value, callback) => {
        const defaultValueArr = conf.__config__.defaultValue;
        if (defaultValueArr.length === 0) {
          const msg =
            (conf.placeholder === undefined
              ? `${conf.__config__.label}不能为空`
              : conf.placeholder) + "必须填写！";
          callback(new Error(msg));
        }else{
          callback();
        }
      };
    },
    organizationTreeValidator(conf) {
      const self = this;
      return (rule, value, callback) => {
        const defaultValue = conf.__config__.defaultValue;
        if (defaultValue) {
          callback();
        } else {
          const msg =`${conf.__config__.label}不能为空`;
          callback(new Error(' '));
        }
      };
    },
       daterangeValidator(conf) {
      const self = this;
      return (rule, value, callback) => {
        const defaultValueArr = conf.__config__.defaultValue;
        const msg =
            (conf.placeholder === undefined
              ? `${conf.__config__.label}不能为空`
              : conf.placeholder) + "必须填写！";
        if(defaultValueArr&&Array.isArray(defaultValueArr)){
          if (defaultValueArr.length === 0) {
          callback(new Error(msg));
        }else{
          callback();
        }
        }else{
            callback(new Error(msg));
        }
      };
    },
    timerangeValidator(conf) {
      const self = this;
      return (rule, value, callback) => {
        const defaultValueArr = conf.__config__.defaultValue;
          const msg =
            (conf.placeholder === undefined
              ? `${conf.__config__.label}不能为空`
              : conf.placeholder) + "必须填写！";
        if(defaultValueArr&&Array.isArray(defaultValueArr)){
          if (defaultValueArr.length > 0) {
            if (defaultValueArr[0] == "") {
              callback(new Error(msg));
            }
            else {
              callback();
            }
          }else {
            callback(new Error(msg));
          }
        }else {
          callback(new Error(msg));
        }
        
      };
    },
    financialValidator(conf) {
      const self = this;
      return (rule, value, callback) => {
        const defaultValue = conf.__config__.defaultValue;
         const msg =
            conf.placeholder === undefined
              ? `${conf.__config__.label}不能为空`
              : conf.placeholder;
        if(defaultValue===''){
          callback(new Error(msg));
        }
        if (defaultValue>=0) {
          callback();
        } else {
         
          callback(new Error(msg));
        }
      };
    },
    changeFields() {
      let authorityList = this.getAuthorityList();
      let taskCommentList = this.getTaskCommentList();
      let taskCommentIds = Object.keys(taskCommentList);
      for (let [key, value] of Object.entries(this.formConf.fields)) {
        if (
          value.__config__.componentName &&
          value.__config__.componentName == "avue-tabs"
        ) {
          if (value.__config__ && value.__config__.childrenObj) {
            let obj = value.__config__.childrenObj;
            for (var i in obj) {
              if (obj[i].length > 0) {
                obj[i].forEach((ele1, cindex) => {

                  if(   ele1.__config__.componentName &&
                      ele1.__config__.componentName == "table"){
                        //子表单权限
                      let tempKey = ele1.__config__.formId;
                      if (authorityList.has(tempKey)) {
                          let tempValue = authorityList.get(tempKey);
                        this.formConf.fields[key].__config__.view = true;
                        let tempChildValue = tempValue.children;
                            let authorityChildrenList = new Map();
                            if(tempChildValue.length>0){
                              tempChildValue.forEach(ele=>{
                                authorityChildrenList.set(ele.fieldsId,ele);
                              });
                            }
                            if(this.formConf.fields[key].__config__.childrenObj[i][cindex].__config__.children&&
                            this.formConf.fields[key].__config__.childrenObj[i][cindex].__config__.children.length>0
                            ){
                              this.formConf.fields[key].__config__.childrenObj[i][cindex].__config__.children = this.formConf.fields[key].__config__.childrenObj[i][cindex].__config__.children.map(ele=>{
                                if( authorityChildrenList.has(ele.__config__.bindTableField)){
                                  let temp = authorityChildrenList.get(ele.__config__.bindTableField);
                                  ele.__config__.required = temp.required;
                                  ele.__config__.view = temp.view;
                                  ele.__config__.edit = temp.edit;
                                }else{
                                  ele.__config__.required = true;
                                  ele.__config__.view = true;
                                  ele.__config__.edit = true;
                                }
                                return ele;
                              });
                            }
                      }else{
                        this.formConf.fields[key].__config__.view = false;
                      }
                    } else{
                      let tempKey = ele1.__config__.formId;
                      //意见框
                      if (
                        this.formConf.fields[key].__config__.childrenObj[i][
                        cindex
                      ].__type__ &&
                        this.formConf.fields[key].__config__.childrenObj[i][
                        cindex
                      ].__type__ == "opinion"
                      ) {
                        //工作流相关意见簿 不显示
                        let selfId =
                          this.formFieldInfo.F_Id +
                          "-" +tempKey;
                        if (taskCommentIds.includes(selfId)) {
                          this.formConf.fields[key].__config__.childrenObj[i][
                        cindex
                      ].__config__.defaultValue = taskCommentList[selfId]
                            ? taskCommentList[selfId]
                            : [];
                        }
                      }

                      if (authorityList.has(tempKey)) {
                        let tempValue = authorityList.get(tempKey);
                        this.formConf.fields[key].__config__.childrenObj[i][
                          cindex
                        ].required = tempValue.required;
                        this.formConf.fields[key].__config__.childrenObj[i][
                          cindex
                        ].view = tempValue.view;
                        this.formConf.fields[key].disabled = tempValue.edit
                          ? false
                          : true;
                        this.formConf.fields[key].__config__.childrenObj[i][
                          cindex
                        ].edit = tempValue.edit;
                        //表单规则创建
                        if (this.formConf.fields[key].__config__.childrenObj[i][
                          cindex
                        ].__config__.required) {
                          let regList = [];
                          let trigger = "change";
                          let validatorStr = "default";
                          if (ComponentList[this.formConf.fields[key].__config__.childrenObj[i][
                          cindex
                        ].__config__.tag]) {
                            trigger = ComponentList[
                              this.formConf.fields[key].__config__.childrenObj[i][
                          cindex
                        ].__config__.tag
                            ].rule.trigger
                              ? ComponentList[this.formConf.fields[key].__config__.childrenObj[i][
                          cindex
                        ].__config__.tag].rule
                                  .trigger
                              : "change";
                            validatorStr = ComponentList[
                              this.formConf.fields[key].__config__.childrenObj[i][
                          cindex
                        ].__config__.tag
                            ].rule.validatorStr
                              ? ComponentList[this.formConf.fields[key].__config__.childrenObj[i][
                          cindex
                        ].__config__.tag].rule
                                  .validatorStr
                              : "default";
                          }
                          let validator = this.defaultValidator(this.formConf.fields[key].__config__.childrenObj[i][
                          cindex
                        ]);
                          if (validatorStr === "upload") {
                            validator = this.uploadValidator(this.formConf.fields[key].__config__.childrenObj[i][
                          cindex
                        ]);
                          }
                          else if(validatorStr === "switch"){
                            validator = this.switchValidator(this.formConf.fields[key].__config__.childrenObj[i][
                          cindex
                        ]);
                          }
                          else if (validatorStr === "checkbox") {
                            validator = this.checkboxValidator(this.formConf.fields[key].__config__.childrenObj[i][
                          cindex
                        ]);
                          }
                          if(this.formConf.fields[key].__config__.childrenObj[i][
                          cindex
                        ].type&&this.formConf.fields[key].__config__.childrenObj[i][
                          cindex
                        ].type === "number"){
                        validator = this.financialValidator(this.formConf.fields[key].__config__.childrenObj[i][
                          cindex
                        ]);
                      }
                           // 时间区间 日期区间 都是数组类型
                          if(this.formConf.fields[key].__config__.childrenObj[i][
                          cindex
                        ].__config__.tag=='el-time-picker'&&this.formConf.fields[key].__config__.childrenObj[i][
                          cindex
                        ].__config__.avueType=='timerange'){
                            validator = this.timerangeValidator(this.formConf.fields[key].__config__.childrenObj[i][
                          cindex
                        ]);
                          }
                          if(this.formConf.fields[key].__config__.childrenObj[i][
                          cindex
                        ].__config__.tag=='el-date-picker'&&this.formConf.fields[key].__config__.childrenObj[i][
                          cindex
                        ].__config__.avueType=='daterange'){
                            validator = this.daterangeValidator(this.formConf.fields[key].__config__.childrenObj[i][
                          cindex
                        ]);
                          }
                          if(this.formConf.fields[key].__config__.childrenObj[i][
                          cindex
                        ].__config__.tag=='avue-input-tree'){
                            validator = this.organizationTreeValidator(this.formConf.fields[key].__config__.childrenObj[i][
                                cindex
                              ]);
                          }
                          const requiredJson = {
                            fieldsIndex: key,
                            required: this.formConf.fields[key].__config__.childrenObj[i][
                          cindex
                        ].__config__.required,
                            trigger,
                            validator
                          };
                          regList.push(requiredJson);
                          //添加 多选框 最小数量 最大数量
                          if(this.formConf.fields[key].__config__.childrenObj[i][
                          cindex
                        ].__config__.tag=='el-checkbox-group'){
                            if(this.formConf.fields[key].__config__.childrenObj[i][
                          cindex
                        ].min||this.formConf.fields[key].__config__.childrenObj[i][
                          cindex
                        ].max){
                              const quantityJson = {
                                fieldsIndex: key,
                                required: this.formConf.fields[key].__config__.childrenObj[i][
                          cindex
                        ].__config__.required,
                                trigger,
                                validator:this.quantityValidator(this.formConf.fields[key].__config__.childrenObj[i][
                          cindex
                        ])
                              };
                              regList.push(quantityJson)
                            }
                          }
                          //添加正则验证
                          if (
                            this.formConf.fields[key].__config__.childrenObj[i][
                          cindex
                        ].__config__.regList &&
                            this.formConf.fields[key].__config__.childrenObj[i][
                          cindex
                        ].__config__.regList.length > 0
                          ) {
                            this.formConf.fields[key].__config__.childrenObj[i][
                          cindex
                        ].__config__.regList.forEach(item => {
                              if (item.pattern) {
                                regList.push({
                                  required: true,
                                  fieldsIndex: key,
                                  validator: this.patternValidator(
                                    eval(item.pattern),
                                    item.message ? item.message : "验证不通过",
                                    this.formConf.fields[key].__config__.childrenObj[i][
                          cindex
                        ]
                                  ),
                                  trigger: "change"
                                });
                              }
                            });
                          }
                          this.formOperationObject.formRules[
                            this.formConf.fields[key].__config__.childrenObj[i][
                          cindex
                        ].__config__.bindTableField
                          ] = regList;
                        }
                      }
                    }
                });
              }
            }
          }
        }else if(   value.__config__.componentName &&
          value.__config__.componentName == "table"){
             //子表单权限
          let tempKey = value.__config__.formId;
          if (authorityList.has(tempKey)) {
              let tempValue = authorityList.get(tempKey);
             this.formConf.fields[key].__config__.view = true;
             let tempChildValue = tempValue.children;
                let authorityChildrenList = new Map();
                if(tempChildValue.length>0){
                  tempChildValue.forEach(ele=>{
                    authorityChildrenList.set(ele.fieldsId,ele);
                  });
                }
                if(this.formConf.fields[key].__config__.children&&this.formConf.fields[key].__config__.children.length>0){
                  this.formConf.fields[key].__config__.children = this.formConf.fields[key].__config__.children.map(ele2=>{
                    if( authorityChildrenList.has(ele2.__config__.bindTableField)){
                      let temp = authorityChildrenList.get(ele2.__config__.bindTableField);
                      ele2.__config__.required = temp.required;
                      ele2.__config__.view = temp.view;
                      ele2.__config__.edit = temp.edit;
                    }else{
                       ele2.__config__.required = true;
                      ele2.__config__.view = true;
                      ele2.__config__.edit = true;
                    }
                    return ele2;
                  });
                }
          }else{
            this.formConf.fields[key].__config__.view = false;
          }
        } else {
          let tempKey = value.__config__.formId;
          if (authorityList.has(tempKey)) {
            let tempValue = authorityList.get(tempKey);
            this.formConf.fields[key].__config__.required = tempValue.required;
            this.formConf.fields[key].__config__.view = tempValue.view;
            this.formConf.fields[key].disabled = tempValue.edit ? false : true;
            this.formConf.fields[key].__config__.edit = tempValue.edit;
            //表单规则创建
            if (this.formConf.fields[key].__config__.required) {
              let regList = [];
              // const regList = this.formConf.fields[key].__config__.regList
              //   ? this.formConf.fields[key].__config__.regList
              //   : [];
              let trigger = "change";
              let validatorStr = "default";
              if (ComponentList[this.formConf.fields[key].__config__.tag]) {
                trigger = ComponentList[
                  this.formConf.fields[key].__config__.tag
                ].rule.trigger
                  ? ComponentList[this.formConf.fields[key].__config__.tag].rule
                      .trigger
                  : "change";
                validatorStr = ComponentList[
                  this.formConf.fields[key].__config__.tag
                ].rule.validatorStr
                  ? ComponentList[this.formConf.fields[key].__config__.tag].rule
                      .validatorStr
                  : "default";
              }
              let validator = this.defaultValidator(this.formConf.fields[key]);
              if (validatorStr === "upload") {
                validator = this.uploadValidator(this.formConf.fields[key]);
              }
              else if(validatorStr === "switch"){
                 validator = this.switchValidator(this.formConf.fields[key]);
              }
              else if (validatorStr === "checkbox") {
                validator = this.checkboxValidator(this.formConf.fields[key]);
              }
              if(this.formConf.fields[key].type&&this.formConf.fields[key].type === "number"){
                        validator = this.financialValidator(this.formConf.fields[key]);
              }
              // 时间区间 日期区间 都是数组类型
              if(this.formConf.fields[key].__config__.tag=='el-time-picker'&&this.formConf.fields[key].__config__.avueType=='timerange'){
                validator = this.timerangeValidator(this.formConf.fields[key]);
              }
              if(this.formConf.fields[key].__config__.tag=='el-date-picker'&&this.formConf.fields[key].__config__.avueType=='daterange'){
                validator = this.daterangeValidator(this.formConf.fields[key]);
              }
              if(this.formConf.fields[key].__config__.tag=='avue-input-tree'){
                validator = this.organizationTreeValidator(this.formConf.fields[key]);
              }
              const requiredJson = {
                fieldsIndex: key,
                required: this.formConf.fields[key].__config__.required,
                trigger,
                validator
              };
              regList.push(requiredJson);
              //添加 多选框 最小数量 最大数量
              if(this.formConf.fields[key].__config__.tag=='el-checkbox-group'){
                if(this.formConf.fields[key].min||this.formConf.fields[key].max){
                  const quantityJson = {
                    fieldsIndex: key,
                    required: this.formConf.fields[key].__config__.required,
                    trigger,
                    validator:this.quantityValidator(this.formConf.fields[key])
                  };
                  regList.push(quantityJson)
                }
              }
              //添加正则验证
              if (
                this.formConf.fields[key].__config__.regList &&
                this.formConf.fields[key].__config__.regList.length > 0
              ) {
                this.formConf.fields[key].__config__.regList.forEach(item => {
                  if (item.pattern) {
                    regList.push({
                      required: true,
                      fieldsIndex: key,
                      validator: this.patternValidator(
                        eval(item.pattern),
                        item.message ? item.message : "验证不通过",
                        this.formConf.fields[key]
                      ),
                      trigger: "change"
                    });
                  }
                });
              }
              this.formOperationObject.formRules[
                this.formConf.fields[key].__config__.bindTableField
              ] = regList;
            }
            //意见框
            if (
              this.formConf.fields[key].__type__ &&
              this.formConf.fields[key].__type__ == "opinion"
            ) {
              //工作流相关意见簿 不显示
              let selfId =
                this.formFieldInfo.F_Id +
                "-" +
                this.formConf.fields[key].__config__.formId;
              if (taskCommentIds.includes(selfId)) {
                this.formConf.fields[
                  key
                ].__config__.defaultValue = taskCommentList[selfId]
                  ? taskCommentList[selfId]
                  : [];
              }
            }
           
          }
        }
      }
    },
    changeApprovalFormData({ fieldsIndex, cur }) {
      //审批流程
      const config = cur.__config__;
      if (this.formData && "{}" != JSON.stringify(this.formData)) {
       // this.isEdit = 3;//编辑
        if (
          this.formData[cur.__config__.bindTable] &&
          config.componentName &&
          config.componentName === "table"
        ) {
          this.formConf.fields[fieldsIndex].__config__.defaultValue = {
            dynamic: this.formData[cur.__config__.bindTable]
          };
        }
        //avue-tab 回显
        if (config.componentName && config.componentName === "avue-tabs") {
          if (config.childrenObj) {
            let obj = config.childrenObj;
            let childrenObj = {};
            for (var key in obj) {
              let tabs = [];
              if (obj[key].length > 0) {
                obj[key].forEach(objEle => {
                  if (
                    objEle.__config__.componentName &&
                    objEle.__config__.componentName === "table"
                  ) {
                    objEle.__config__.defaultValue = {
                      dynamic: this.formData[objEle.__config__.bindTable]
                    };
                  }
                  if (
                    objEle.__config__.bindTable &&
                    objEle.__config__.bindTableField &&
                    this.formData[objEle.__config__.bindTable][
                      objEle.__config__.bindTableField
                    ]
                  ) {
                    if (
                      objEle.__config__.tag === "el-checkbox-group" ||
					  objEle.__config__.tag === "el-mutiple-input"
                    ) {
                      let configVal =this.formData[
                        objEle.__config__.bindTable
                      ][objEle.__config__.bindTableField];
                      if(configVal.includes(',')){
                        objEle.__config__.defaultValue = configVal.split(",");
                      }else{
                        objEle.__config__.defaultValue = [configVal];
                      }
					  this.getMutipleAllData(objEle.__config__)
                    } else if(objEle.__config__.tag === "el-date-picker" ||
                      objEle.__config__.tag === "el-time-picker"){
                        let configVal =this.formData[
                        objEle.__config__.bindTable
                      ][objEle.__config__.bindTableField]+'';
                      if(configVal.includes(',')){
                        objEle.__config__.defaultValue = configVal.split(",");
                      }else{
                        objEle.__config__.defaultValue = configVal;
                      }
                      }else {
                      objEle.__config__.defaultValue = this.formData[
                        objEle.__config__.bindTable
                      ][objEle.__config__.bindTableField];
                    }
                  }
                  tabs.push(objEle);
                });
              }
              childrenObj[key] = tabs;
            }
            this.formConf.fields[
              fieldsIndex
            ].__config__.childrenObj = childrenObj;
          }
        }
        if (
          cur.__config__.bindTable &&
          cur.__config__.bindTableField &&
          this.formData[cur.__config__.bindTable] &&
          this.formData[cur.__config__.bindTable][cur.__config__.bindTableField]
        ) {
			
          this.formConf.fields[
            fieldsIndex
          ].__config__.defaultValue = this.formData[cur.__config__.bindTable][
            cur.__config__.bindTableField
          ];
          if (
            this.formConf.fields[fieldsIndex].__config__.tag ===
              "el-checkbox-group" ||
			this.formConf.fields[fieldsIndex].__config__.tag ===
			  "el-mutiple-input"
          ) {
			  
            let configVal =this.formData[cur.__config__.bindTable][
              cur.__config__.bindTableField
            ];
            if(configVal.includes(',')){
                this.formConf.fields[
                fieldsIndex
              ].__config__.defaultValue = configVal.split(",");
            }else{
                this.formConf.fields[
                fieldsIndex
              ].__config__.defaultValue = [configVal];
            }
			this.getMutipleAllData(this.formConf.fields[fieldsIndex].__config__)
          }
          if (this.formConf.fields[fieldsIndex].__config__.tag ===
              "el-date-picker" ||
            this.formConf.fields[fieldsIndex].__config__.tag ===
              "el-time-picker"
          ) {
            let configVal =this.formData[cur.__config__.bindTable][
              cur.__config__.bindTableField
            ]+'';
            if(configVal.includes(',')){
                this.formConf.fields[
                fieldsIndex
              ].__config__.defaultValue = configVal.split(",");
            }else{
                this.formConf.fields[
                fieldsIndex
              ].__config__.defaultValue = configVal;
            }
          }
        }
      }
    },
	//多选弹层 表单编辑时数据回显处理
	async getMutipleAllData(config){	
		let datatype=config.dataType;
		let saveField = datatype == 'dataItem' ? 'F_ItemValue' : config.saveField
		let showField = datatype == 'dataItem' ? 'F_ItemName' : config.showField;
		
		if(datatype=='dataSource') {
		  let res=await getDataBySQL(config.dataSource)
		  if(res?.data?.data) this.changeMutipleData(config,res.data.data,saveField,showField)
		}
		if(datatype=='dataSql') {
			let res=await getDbLinksTestSql(config.database,{sql:config.sql})
			if(res?.data?.data) this.changeMutipleData(config,res.data.data,saveField,showField)			
		}
		if(datatype=='dataItem'){
			let res=await getDataDetail(config.dataItem)
			if(res?.data?.data) this.changeMutipleData(config,res.data.data,saveField,showField)
		}
	},	
	changeMutipleData(config,data,saveField,showField){
		let arr=config.defaultValue;
		let arr1=[];
		arr.forEach(it=>{
			let temp=data.find(o=>{return o[saveField]==it});
			if(temp){
				arr1.push(temp[showField])
			}
		})
		this.$set(config,'showValue',arr1.join(','));		  
	},
    changeData() {
      const self = this; // 规则验证需要绑定vue实例this
      this.formConf.fields.forEach((cur, fieldsIndex) => {
        const config = cur.__config__;
        if (config.tag === "h2") {
          //标题 忽略
          return;
        }
        if (config.tag === "el-divider") {
          //分割线 忽略
          return;
        }
        //表单提交数据（tablename绑定）
        if (!this.formOperationObject.formModel[config.bindTable]) {
          this.formOperationObject.formModel[config.bindTable] = {};
        }

        if (config.componentName && config.componentName === "table") {
          this.formConf.fields[fieldsIndex].__config__.defaultValue = {
            dynamic: []
          };
        }
        if (!this.formOperationObject.mainTableName) {
          if (!config.componentName || config.componentName !== "table") {
            this.formOperationObject.mainTableName = config.bindTable;
          }
        }
        this.changeApprovalFormData({ fieldsIndex, cur });
        if (cur.__info__ === true && cur.__type__ === "info") {
          //信息体 赋值
          this.formConf.fields[fieldsIndex].__config__.tag = "info";
        }
        if (cur.__info__ === true && cur.__type__ === "avue-information-body") {
          //信息体 赋值
          this.formConf.fields[fieldsIndex].__config__.tag = "info";
        }
      });
    },
	handleFilterableClick(scheme) {
	  let conf = scheme.__config__;

	    let params = {};
	    params.title = conf.label + this.$t('optionRecord');
	    params.model = scheme.__vModel__;
	    params.formId = conf.formId;
	    params.dataType = conf.dataType;
		params.avueType = conf.avueType;
	    switch (conf.dataType) {
	      case "dataSource":
	        params.dataSource = conf.dataSource;
	        params.tabName = "base";
	        break;
	      case "dataSql":
	        params.dataSource = conf.database;
	        params.tabName = "sql";
	        params.sqlStr = conf.sql;
	        break;
	      case "dataItem":
	        params.dataSource = conf.dataItem;
	        params.fields = ["F_ItemName", "F_ItemValue"];
	        params.tabName = "item";
			conf.saveField='F_ItemValue'
	        break;
	    }
	    params.showField = conf.showField;
	    params.saveField = conf.saveField;
	    params.autoBindFields = conf.autoBindFields;
		params.defaultValue=conf.defaultValue;
	    this.$event.$emit("openFilterableDataDialog", params);

	},
    renderForm(createElement) {
      return this.formConf.fields.map((scheme, index) => {
        const config = scheme.__config__;
        if (config.layout === "colFormItem") {
          return this.renderColFormItem(
            createElement,
            config.layout,
            scheme,
            index
          );
        } else if (config.layout === "rowFormItem") {
          return this.renderRowFormItem(
            createElement,
            config.layout,
            scheme,
            index
          );
        } else {
          return "";
        }
      });
    },
    renderColFormItem(createElement, item, scheme, fieldsIndex) {
      const config = scheme.__config__;
      let labelWidth = config.labelWidth ? `${config.labelWidth}px` : null;
      if (config.showLabel === false) {
        labelWidth = "0";
      }
      if (!config.view) {
        return "";
      }
      let renderTag = ComponentList[config.tag]
        ? ComponentList[config.tag].renderTag
        : "ElComponent";
      const vnodes = createElement(renderTag, {
        props: { fieldsIndex, formConf: this.formConf,curFormId: config.formId, isEdit: this.isEdit }
      });
	  let showNode=''
	  if(config.tag=="el-mutiple-input"){
	  	showNode=createElement('el-input',{
	  		props:{
	  			value:config.showValue,
				'suffix-icon':'el-icon-more'								
	  		},
	  		attrs:{
	  			placeHolder:scheme.placeholder
	  		},
	  		on:{
	  			focus:()=>this.handleFilterableClick(scheme)
	  		}
	  	})
	  }
	  let lgmarkString = '';
	  /**
	   * author:yyp
	   * time : 2021.10.30
	   * desc ：多语言翻译 当前form label
	   */
	  if(config.F_LgMarkCode === '' || config.F_LgMarkCode === null|| config.F_LgMarkCode === undefined){
	    lgmarkString = config.label
	  }
	  else{
	    lgmarkString = this.$t(config.F_LgMarkCode);
	  } 
    	if(config.tag=="el-mutiple-input"){
			return (
			  <el-col span={config.span}>
			    <el-form-item
			      label-width={labelWidth}
			      prop={config.bindTableField}
			      label={config.showLabel ? lgmarkString  : ''}
			    >
			      {showNode}
				  <el-form-item
				    prop={config.bindTableField}
					style="display:none"
				  >
				    {vnodes}
				  </el-form-item>
			    </el-form-item>
			  </el-col>
			)
		}else{
			return (
			  <el-col span={config.span}>
			    <el-form-item
			      label-width={labelWidth}
			      prop={config.bindTableField}
			      label={config.showLabel ? lgmarkString  : ''}
			    >
			      {vnodes}
			    </el-form-item>
			  </el-col>
			)
		}
    },
    renderRowFormItem(createElement, item, scheme, fieldsIndex) {
      if(scheme.__config__&&scheme.__config__.view==false){
        return '';
      }
      let child = this.renderChildren(createElement, scheme, fieldsIndex);
      let slots = child;
      if(scheme.__config__.componentName && scheme.__config__.componentName === 'table'){
        return child
      } else if (scheme.type === "flex") {
        // 如果是表格类型
        slots = this.renderFlexRow(scheme, child);
      }
      return (
        <el-col span={scheme.span}>
          <el-row gutter={scheme.gutter}>{slots}</el-row>
        </el-col>
      );
    },

    renderChildren(createElement, scheme, fieldsIndex) {
      const config = scheme.__config__;
      if (config.componentName && config.componentName === "table") {
        return this.renderTable(createElement, config, fieldsIndex);
      }
      //avue-tabs 绘制
      if (config.componentName && config.componentName === "avue-tabs") {
        return this.renderTabs(createElement, config, fieldsIndex);
      }
      if (!Array.isArray(config.children)) {
        return null;
      }
      return this.renderForm(config.children);
    },
    renderTable(createElement, config, fieldsIndex) {
       return createElement('CustomeTable', {props: { fieldsIndex, formConf: this.formConf, isEdit: this.isEdit },ref:'avueTable'+config.formId});
    },
    renderTabs(createElement, config, fieldsIndex) {
      return createElement("CustomeTabs", {
        props: { fieldsIndex, formConf: this.formConf, isEdit: this.isEdit }
        ,ref:'FormTab'+fieldsIndex
      });
    },
    renderFlexRow(scheme, child) {
      return (
        <el-row
          type={scheme.type}
          justify={scheme.justify}
          align={scheme.align}
        >
          {child}
        </el-row>
      );
    },
    getNewObj(){
      const newObj = {};
      let self = this;
      this.formConf.fields.forEach(el => {
        if (el.__config__.componentName === "table") {
          if (!newObj[el.__config__.bindTable]) {
            newObj[el.__config__.bindTable] = [];
          } else {
            newObj[el.__config__.bindTable] = el.__config__.defaultValue;
          }

          let tmp = el.__config__.defaultValue.dynamic;
          if(tmp&&tmp.length>0){
          tmp.forEach(function(item) {
            let itemChild = { ...item }
             delete itemChild._index
            for (let [key, value] of Object.entries(itemChild)) {
              if(key.includes('$')){
                delete itemChild[key];
              }
            }
            newObj[el.__config__.bindTable].push(itemChild)
          })
          }

        } else if (el.__config__.componentName == "avue-tabs") {
            let fieldInfo = this.getFieldsByTab(
              el.__config__.childrenObj,
              newObj
            );
            let bindTable = "";
            if (fieldInfo && fieldInfo.length) {
              bindTable = fieldInfo[0].bindTable;
              if (!newObj[bindTable]) {
                newObj[bindTable] = {};
              }
            }
            fieldInfo.map(item => {
              if (
                item.tag === "el-checkbox-group" ||
                item.tag === "el-date-picker" ||
                item.tag === "el-time-picker"
              ) {
                newObj[bindTable][item.bindTableField] = Array.isArray(
                  item.defaultValue
                )
                  ? item.defaultValue.join(",")
                  : item.defaultValue;
              } else if (item.tag === "avue-select-area") {
                //行政区域
                newObj[bindTable][item.bindTableField] = Array.isArray(
                  item.defaultValue
                )
                  ? item.defaultValue.join(",")
                  : item.defaultValue;
              } else {
                newObj[bindTable][item.bindTableField] = item.defaultValue;
              }
            });
          }else {
            if (el.__config__.bindTable) {
              if (!newObj[el.__config__.bindTable]) {
                newObj[el.__config__.bindTable] = {};
              }
              if (
                el.__config__.tag === "el-checkbox-group" ||
                el.__config__.tag === "el-date-picker" ||
                el.__config__.tag === "el-time-picker"
              ) {
                newObj[el.__config__.bindTable][
                  el.__config__.bindTableField
                ] = Array.isArray(el.__config__.defaultValue)
                  ? el.__config__.defaultValue.join(",")
                  : el.__config__.defaultValue;
              }else if ( el.__config__.tag === "el-upload"){
                 newObj[el.__config__.bindTable][el.__config__.bindTableField] =
                  el.__config__.defaultValue;
              } else if (el.__config__.tag === "avue-select-area") {
                //行政区域
                newObj[el.__config__.bindTable][
                  el.__config__.bindTableField
                ] = Array.isArray(el.__config__.defaultValue)
                  ? el.__config__.defaultValue.join(",")
                  : el.__config__.defaultValue;
              } else {
                newObj[el.__config__.bindTable][el.__config__.bindTableField] =
                  el.__config__.defaultValue;
              }
            }
          }
      });
      let mainParams = {};
      mainParams.F_FormId = this.formInfos.SchemeInfo.F_Id;
      let formParams = {};
      for (const key in newObj) {
          formParams[key] = newObj[key];
      }
      return formParams;
    },
    async submitForm() {
      //父页面提交表单  returnData {code:0,params,fileValue}// 0 提交失败 1不需要提交 2 提交数据
      let returnData = { code: 0, params: {} ,fileValue:[],draftList:{}};
       returnData.draftList =  this.getNewObj();
      // let formValid = false;
      let validataArry = []
		for(const el in this.$refs){
      if(el.includes('FormTab')){
          	for(const el2 in this.$refs[el].$refs){
              if(el2.includes('avueTable')){
                let value = this.$refs[el].$refs[el2].getDynamicDefaultValue();
                if(value&&value.length>0){
                    const promise4  = new Promise((resolve,reject) => {
                      this.$refs[el].$refs[el2].validate(valid =>{
                          resolve(valid)
                        })
                    })			
                    validataArry.push(promise4)
                }
              }else{
                const promise2  = new Promise((resolve,reject) => {
                      this.$refs[el].$refs[el2].validate(valid =>{
                        resolve(valid)
                      })
                    })			
                validataArry.push(promise2)
              }
            }
        }else if(el.includes('avueTable')){
          let value = this.$refs[el].getDynamicDefaultValue();
          if(value&&value.length>0){
              const promise3  = new Promise((resolve,reject) => {
                this.$refs[el].validate(valid =>{
                    resolve(valid)
                  })
              })			
              validataArry.push(promise3)
          }
        }else{
          const promise  = new Promise((resolve,reject) => {
          this.$refs[el].validate(valid =>{
              resolve(valid)
            })
          })			
			    validataArry.push(promise)
      }
		}
		let res=await Promise.all(validataArry)
		if(res.includes(false)) {
       return returnData;
    }
     
      let needSubmitForm = true;
      const newObj = {};
      this.formConf.fields.forEach(el => {
        if (el.__config__.componentName === "table") {
          if (!newObj[el.__config__.bindTable]) {
            newObj[el.__config__.bindTable] = [];
          } else {
            newObj[el.__config__.bindTable] = el.__config__.defaultValue;
          }

          let tmp = el.__config__.defaultValue.dynamic;
          if(tmp&&tmp.length>0){
          tmp.forEach(function(item) {
            let itemChild = { ...item }
             delete itemChild._index
            for (let [key, value] of Object.entries(itemChild)) {
              if(key=='_index'){
                 delete itemChild[key];
              }
              if(key.includes('$')){
                delete itemChild[key];
              }else{
                if(Array.isArray(value)){
                    itemChild[key] = value.join(",")
                }
              }
            }
            newObj[el.__config__.bindTable].push(itemChild)
          })
          }
        } else {
          // if (el.__config__.edit) {
          if (el.__config__.componentName === "table") {
          } else {
            if (el.__config__.bindTable) {
              if (!newObj[el.__config__.bindTable]) {
                newObj[el.__config__.bindTable] = {};
              }
              if (
                el.__config__.tag === "el-checkbox-group" ||
                el.__config__.tag === "el-date-picker" ||
                el.__config__.tag === "el-time-picker" ||
				el.__config__.tag === "el-mutiple-input"
              ) {
                newObj[el.__config__.bindTable][
                  el.__config__.bindTableField
                ] = Array.isArray(el.__config__.defaultValue)
                  ? el.__config__.defaultValue.join(",")
                  : el.__config__.defaultValue;
              }else if ( el.__config__.tag === "el-upload"){
                if(el.__config__.defaultValue){
                  returnData.fileValue.push(el.__config__.defaultValue);
                }
                 newObj[el.__config__.bindTable][el.__config__.bindTableField] =
                  el.__config__.defaultValue;
              } else if (el.__config__.tag === "avue-select-area") {
                //行政区域
                newObj[el.__config__.bindTable][
                  el.__config__.bindTableField
                ] = Array.isArray(el.__config__.defaultValue)
                  ? el.__config__.defaultValue.join(",")
                  : el.__config__.defaultValue;
              } else {
                 if(Array.isArray(el.__config__.defaultValue)){
                  newObj[el.__config__.bindTable][el.__config__.bindTableField] =
                    el.__config__.defaultValue.join(",")
                    }else{
                      newObj[el.__config__.bindTable][el.__config__.bindTableField] =
                    el.__config__.defaultValue
                  }
              }
            }
          }
          // }
          if (el.__config__.componentName == "avue-tabs") {
            let fieldInfo = this.getFieldsByTab(
              el.__config__.childrenObj,
              newObj
            );
            let bindTable = "";
            if (fieldInfo && fieldInfo.length) {
              bindTable = fieldInfo[0].bindTable;
              if (!newObj[bindTable]) {
                newObj[bindTable] = {};
              }
            }
            fieldInfo.map(item => {
              if (
                item.tag === "el-checkbox-group" ||
                item.tag === "el-date-picker" ||
                item.tag === "el-time-picker"||
				item.tag === "el-mutiple-input"
              ) {
                newObj[bindTable][item.bindTableField] = Array.isArray(
                  item.defaultValue
                )
                  ? item.defaultValue.join(",")
                  : item.defaultValue;
              } else if (item.tag === "avue-select-area") {
                //行政区域
                newObj[bindTable][item.bindTableField] = Array.isArray(
                  item.defaultValue
                )
                  ? item.defaultValue.join(",")
                  : item.defaultValue;
              } else {
                newObj[bindTable][item.bindTableField] = item.defaultValue;
              }
            });
          }
        }
      });
      if (JSON.stringify(newObj) == "{}") {
        needSubmitForm = false;
      }
      let formParams = {};
      if (needSubmitForm) {
        for (const key in newObj) {
          formParams[key] = newObj[key];
        }
        var mainParams = {};

        if (this.formInfos.SchemeInfo) {
          mainParams.F_FormId = this.formInfos.SchemeInfo.F_Id; // 表单ID(后端需要)
          mainParams.F_Name = this.formInfos.SchemeInfo.F_Name; // 表单名
        }
        var params = Object.assign(mainParams, formParams);

        returnData.code = 2;
        returnData.params = params;
        return returnData;
      } else {
        returnData.code = 1;
        returnData.params = {};
        return returnData;
      }
    },
    getFieldsByTab(childrenObj, newObj) {
      let _arr = [];
      if (!childrenObj || childrenObj instanceof Object) {
        for (let key in childrenObj) {
          let children = childrenObj[key];
          children.map(item => {
            if (item.__config__.componentName == "table") {
              let children = item.__config__.children || [];
              let bindTable = "";
              children.map(el => {
                bindTable = el.__config__.bindTable;
                if (!newObj[el.__config__.bindTable]) {
                  newObj[el.__config__.bindTable] = [];
                }
              });
              // let self = this;
              let tmp = (item.__config__&&item.__config__.defaultValue&&item.__config__.defaultValue.dynamic)?item.__config__.defaultValue.dynamic:[];
              if(tmp&&Array.isArray(tmp)&&tmp.length>0){
                tmp.forEach((itemChild) =>{
                  if(itemChild._index){
                    delete itemChild._index
                  }
                for (let [key, value] of Object.entries(itemChild)) {
                   if(key=='_index'){
                    delete itemChild[key];
                  }
                  if(key.includes('$')){
                    delete itemChild[key];
                  }else{
                    if(Array.isArray(value)){
                        itemChild[key] = value.join(",")
                    }
                  }
                }
                newObj[bindTable].push(itemChild)
              })
              }
              

            } else {
              if (item.__config__.bindTable && item.__config__.bindTableField) {
                let _obj = {};
                _obj.bindTableField = item.__config__.bindTableField;
                _obj.defaultValue = item.__config__.defaultValue;
                _obj.bindTable = item.__config__.bindTable;
                _obj.tag = item.__config__.tag;
                _arr.push(_obj);
              }
            }
          });
        }
      }
      return (() => {
        return _arr;
      })();
    }
  }
};
</script>
<style scoped>
div /deep/ .el-table__body,
div /deep/ .el-table__footer,
div /deep/ .el-table__header {
  width: 100% !important;
}
.el-form-item {
  margin-top: 0;
  margin-bottom: 18px !important;
}
div /deep/ .avue-input-tree{
  display: block;
}
</style>
